package cn.huanghuai.reggie.controller.filter;

import cn.huanghuai.reggie.common.BaseContext;
import cn.huanghuai.reggie.common.R;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 检查是否登录的过滤器
 */
@Slf4j
@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
public class LoginCheckFilter implements Filter {

    //路径匹配器，支持通配符。因为定义不需要处理的uri时，是字符串，含有通配符(**)，直接匹配是不能生效的
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        //强转为HttpServletRequest,HttpServletResponse
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //1.获取本次请求的uri
        String requestURI = request.getRequestURI();
            //定义不需要处理的uri
        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                //静态资源放行，访问页面可以，但是数据不能看到
                "/backend/**",
                "/front/**",
                "/common/upload",
                "/common/download",
                "/user/sendMsg",
                "/user/login"
        };

//        log.info("拦截到：{}",requestURI);

        //2.判断本次请求是否需要处理(封装成方法使用)
        boolean check = check(urls, requestURI);
        //3.如果不需要处理，直接放行并return
        if (check){
            filterChain.doFilter(request, response);
            return;
        }

        //4-1.判断员工登录状态，如果登录，则直接放行
        if (request.getSession().getAttribute("employee") != null){
            //将本次线程的id放入BaseContext中
            Long empId = (Long) request.getSession().getAttribute("employee");
            BaseContext.setCurrentId(empId);

            filterChain.doFilter(request, response);
            return;
        }
        //4-2.判断用户登录状态，如果登录，则直接放行
        if (request.getSession().getAttribute("user") != null){
            //将本次线程的id放入BaseContext中
            Long userId = (Long) request.getSession().getAttribute("user");
            BaseContext.setCurrentId(userId);

            filterChain.doFilter(request, response);
            return;
        }

        //5.如果未登录，通过输出流的方式，向客户端页面响应数据。返回这个东西，前端代码会处理跳转
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;
    }

    /**
     * 路径匹配，检查本次请求是否需要放行
     * @param urls
     * @param requestURI
     * @return
     */
    public boolean check(String[] urls, String requestURI){
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, requestURI);
            if (match)
                return true;
        }
        return false;
    }

}
